package utils;

import java.sql.*;

public class DBUtil {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql:///dorm?useSSL=false&characterEncoding=utf8", "root", "shy666nb");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
    public static ResultSet query(String sql,Object ...keys) {
        ResultSet rs = null;
        try {
            Connection conn = getConn();
            PreparedStatement pst = conn.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
            rs = pst.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }
    public static int update(String sql,Object ...keys) {
        int rs = 0;
        try {
            Connection conn = getConn();
            PreparedStatement pst = conn.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }
            rs = pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }
}
